
<div class="mt-9 max-w-md">
  
    <div class="grid grid-cols-1 gap-6">
      {#if  wallet!=""}
       <span>钱包地址： {wallet}</span>
       {:else}
       <MButton on:click={connect} title="连接钱包"/>
      {/if}
      <h1>查看提议 #{id}</h1>
     <div><span>提议名称：</span><span>{data.title}</span></div> 
     <div><span>提议详情：</span><span>{data.content}</span></div> 
     <div><span>提议类别：</span><span>{data.ptype==="0"?"提币":(data.ptype==="1"?"添加议员":"撤销议员")}</span></div> 
     <div><span>发起人：</span><span>{data.created_by}</span></div> 
     <div><span>创建日期：</span><span>{(new Date(parseInt(data.created_at)*1000)).toString()}</span></div> 
     {#if data.status==="1"}
     <div><span>结束日期</span><span>{(new Date(parseInt(data.finished_at)*1000)).toString()}</span></div> 
    {/if}

    {#if data.ptype==="0"}
    <div><span>转账币种：</span><span>{extra.token}</span></div> 
    <div><span>收款金额：</span><span>{extra.amount}</span></div> 
    <div><span>收款地址：</span><span>{extra.target_address}</span></div> 
    {:else}
    <div><span>议员地址：</span><span>{extra}</span></div> 
   {/if}

     <div><span>赞成票：</span><span>{approve_votes.length}</span>
    <table class="table-auto">
      <tbody>
        {#each approve_votes as item}
        <tr>
          <td>  <span>{item}</span></td>
        </tr>
      {/each}
      </tbody>
    </table>

    </div> 
 
     <div><span>反对票：</span>   <span>{reject_votes.length}</span>


    <table class="table-auto">
   
      <tbody>
        {#each reject_votes as item}
        <tr>
          <td>  <span>{item}</span></td>
        </tr>
      {/each}
      </tbody>
      
      </div> 
     <div><span>投票状态：</span><span>{data.status==="0"?"进行中":"已结束"}</span></div> 
     <div><span>投票结果：</span><span>{data.result==="0"?"投票中":(data.result==="1"?"通过":"不通过")}</span></div> 

     <MButton on:click={()=>vote(1)} title="赞成"/>
     <MButton on:click={()=>vote(2)} title="反对"/>
      <MButton on:click={()=>close()} title="结束提议"/>
    </div>
    </div>

    <script lang="ts">
    import { onMount } from 'svelte';
    import {abi} from '../../constants'
    import MButton from '../../components/MButton.svelte'
    import MTextInput from '../../components/MTextInput.svelte'

    export let id="";
    let wallet = ""
    let contract = ""
    export let address = ""
    let data =""
    let approve_votes=[]
    let reject_votes=[]
    let extra = {} 
    
    onMount(async () => {
      if (window.ethereum) {
        let web3 = new Web3(window.ethereum);
        let c = new web3.eth.Contract(abi,address,{
            from:"0x948B3c65b89DF0B4894ABE91E6D02FE579834F8F"
          })
          const proposal_detail_basic  = await c.methods.proposal_detail_basic(id).call()

          if(proposal_detail_basic.ptype==="0"){
             extra  = await c.methods.proposal_detail_withdraw(id).call()
          }else{
             extra  = await c.methods.proposal_detail_voter_address(id).call()
          }

          console.log(extra)
          approve_votes = await c.methods.getApproveVotes(id).call()
          reject_votes = await c.methods.getRejectVotes(id).call()
          console.log({proposal_detail_basic,approve_votes,reject_votes}) 
          data=proposal_detail_basic
      }
	  });



    const connect = ()=>{
    if (window.ethereum) {
      window.ethereum
        .request({ method: "eth_requestAccounts" })
        .then((accounts)=>{
          if (accounts.length === 0) { Swal.fire('未检测到 Web3 环境，如你已经安装请启用并刷新页面!')} else {
            wallet=accounts[0]
            let web3 = new Web3(window.ethereum);
            contract = new web3.eth.Contract(abi,address,{
            from:wallet
            })
        }
        }).catch((err) => {
        Swal.fire('未检测到 Web3 环境，如你已经安装请启用并刷新页面!')
        console.error(err);
        })
    } else { Swal.fire('未检测到 Web3 环境，如你已经安装请启用并刷新页面!')  }
   }


   const vote = async (opinion)=>{
    if(!contract){
        Swal.fire('未连接钱包')
        return
    }
    try{
        const canVote  = await contract.methods.canVote(id).call()
        console.log({canVote})
        // 检查是否有投票权 1
        // 检查投票是否结束 2
        // 检查是否投过赞成票 3
        // 检查是否投过反对票 4
        const canVoteMsg ={
          "1":"您没有投票权",
          "2":"该提议已经结束",
          "3":"您投过赞成票了",
          "4":"您投过反对票了"
        }

        if(canVote!=0){
          Swal.fire(canVoteMsg[canVote]) 
          return ;
        }

        const res = await contract.methods.vote(id,opinion).send({});
        console.log({res})
    }catch(e){
      console.error(e)
    }
   }

   const close =async ()=>{
    if(!contract){
        Swal.fire('未连接钱包')
        return
    }

    try{

      const canClose  = await contract.methods.canClose(id).call()
        console.log({canClose})
        // 检查提议是否存在 1
        // 检查提议是否为发起人 2
        // 检查提议是否结束 3
        // 检查是投票数是否达标 4
        const canCloseMsg ={
          "1":"提议不存在",
          "2":"发起人才能结束提议",
          "3":"提议已经结束",
          "4":"赞成票或反对票达到总票的50% 或 投票率达到80%才可以结束提议"
        }
        if(canClose!=0){
          Swal.fire(canCloseMsg[canClose]) 
          return ;
        }
        const res = await contract.methods.closeProposal(id).send({});
        console.log({res})
    }catch(e){
      console.error(e)
    }
   }

 </script>
 